
import React, { useState, useEffect } from 'react';
import './index.less';
import * as Inter from '../interface';

// 函数防抖处理-输入
let lastTime: any; // eslint-disable-line
let timer: NodeJS.Timeout; // eslint-disable-line
let outside = false;
const defaultSize = 'mod'; //默认大小

const UiSelect = (props: Inter.Iprops) => {
  const { options, searchVisible, size, defaultValue, change } = props;
  const [visible, setVisible] = useState(false); // 选项面板-显示
  const [list, setList] = useState<Array<Inter.Ioption>>(options || []); //选项列表-当前显示
  const [checked, setChecked] = useState<string | number>(defaultValue || ''); //选中的值
  const [search, setSearch] = useState(''); //搜索的值
  const [inputValue, setInputValue] = useState(''); //输入框值
  const [placeholder, setPlaceholder] = useState(''); //输入框显示提示
  const [value, setValue] = useState(''); //指示图标
  const [checkOption, setCheckOption] = useState<Inter.Ioption>(Inter.defaultOption); //选中的对象
  // 防抖
  function debounce(fn: () => void, wait: number) {
    const now: any = new Date(); //eslint-disable-line
    if (lastTime - now < wait) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn();
      lastTime = +new Date();
    }, wait);
  }
  // 进入搜索界面
  function getFcous() {
    if (searchVisible) {
      setInputValue(search);
    }
  }
  // 输入搜索关键字
  function inputValueFn(e) {
    const val = e.target.value;
    setInputValue(val);
    setSearch(val);
    debounce(() => {
      searchFn(val);
    }, 500);
  }
  // 清理输入框
  function clearFn() {
    if (search === '') {
      setChecked('');
      setInputValue('');
      setCheckOption(Inter.defaultOption);
    } else {
      setSearch('');
      setInputValue(checkOption.label);
      setList(options);
    }
  }
  //click 选中事件
  function optionClick(item: Inter.Ioption) {
    setChecked(item.value);
    setCheckOption(item);
    setInputValue(item.label);
    setSearch('');
    setVisible(false);
  }
  // 本地模糊搜索
  function searchFn(value: string) {
    console.log(value);
    const arr = options.filter(item => {
      return item.label.includes(value);
    });
    setList([...arr]);
  }
  // 点击空白判断
  function onSpaceFn() {
    if (outside) {
      outside = false;
    } else {
      setVisible(false);
    }
  }
  // 点击输入框
  function inputClick() {
    if (!visible) {
      setVisible(true);
    }
  }
  //render
  function renderOption() {
    if (list.length === 0) {
      return <div className="ui-select-none">暂无数据~</div>;
    } else {
      return list.map((item, index) => {
        return (
          <div onClick={optionClick.bind(this, item)} key={index} className={`ui-select-option ${checked === item.value ? 'ui-select-checked' : ''}`}>
            {item.label}
          </div>
        );
      });
    }
  }
  // 初始化值
  function initFn() {
    if (defaultValue && options) {
      const result = options.filter(item => {
        return item.value === defaultValue;
      });
      if (result[0]) {
        setCheckOption(result[0]);
        setPlaceholder(result[0].label);
        setInputValue(result[0].label);
      }
    }
  }
  useEffect(() => {
    setPlaceholder(checked === '' ? '请选择' : checkOption.label);
    if (change) {
      change(checked);
    }
  }, [checked]);
  useEffect(() => {
    initFn();
    window.addEventListener('mouseup', onSpaceFn);
    return () => {
      window.removeEventListener('mouseup', onSpaceFn);
    };
  }, []);
  return (
    <div
      className={`ui-select ui-select-${size ? size : defaultSize}`}
      onMouseDown={() => {
        outside = true;
      }}
    >
      <div className={`ui-select-reveal ${visible ? 'ui-select-focus' : ''}`} onClick={inputClick.bind(this)}>
        <input
          readOnly={!searchVisible || (options && options.length < 1)}
          onInput={inputValueFn.bind(this)}
          onFocus={getFcous.bind(this)}
          value={inputValue}
          className="ui-select-input"
          placeholder={placeholder}
          type="text"
        />
        <i
          style={{ display: `${searchVisible ? '' : 'none'}` }}
          onClick={clearFn.bind(this)}
          className={`iconfont icon-close-circle ${inputValue === '' ? 'close-hidden' : ''}`}
        ></i>
        <i className="iconfont icon-xiabian" onClick={setVisible.bind(this, !visible)}></i>
      </div>
      <div className={`ui-select-panel ui-select-${visible ? 'show' : ''}`}>{renderOption()}</div>
    </div>
  );
};

export default UiSelect;
